import {
  RECEIVE_USER_INFO,
  RECEIVE_CONTACTS,
  RECEIVE_FRIEND_REQUEST_LIST,
  RECEIVE_CURRENTSESSION,
  UPDATE_SESSIONLIST
} from './mutations-type'
import {
  reqContacts,
  reqGetFriendRequestList
} from '@/api/index.js'

export default {
  saveUserInfo ({commit}, userInfo) { // 登录以后保存用户信息
    // 将用户信息存储到localStorage中
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
    commit(RECEIVE_USER_INFO, {userInfo})
  },
  autoLogin ({commit}) { // 刷新自动登录
    if (localStorage.getItem('userInfo')) {
      const userInfo = JSON.parse(localStorage.getItem('userInfo'))
      commit(RECEIVE_USER_INFO, {userInfo})
    }
  },
  removeUserInfo ({commit}) { // 退出登录后移除用户信息
    if (localStorage.getItem('userInfo')) {
      localStorage.removeItem('userInfo') // 从localStorage移除userInfo
      const userInfo = {}
      commit(RECEIVE_USER_INFO, {userInfo}) // 重置vuex的userInfo
    }
  },
  async getContacts ({commit, state}) { // 获取并保存通讯录
    const userId = state.userInfo.id
    const result = await reqContacts(userId)
    if (result.success) {
      const contacts = result.data
      commit(RECEIVE_CONTACTS, {contacts})
    }
  },
  async getFriendRequestList ({commit, state}) { // 获取好友请求列表
    const userId = state.userInfo.id
    const result = await reqGetFriendRequestList(userId)
    if (result.success) {
      const friendRequestList = result.data.reverse()
      commit(RECEIVE_FRIEND_REQUEST_LIST, {friendRequestList})
    }
  },
  getCurrentSession ({commit}, {currentSession, msg, count}) { // 获得currentSession，->mutation->state
    commit(RECEIVE_CURRENTSESSION, {currentSession, msg, count})
  },
  updateSessionList ({commit}, currentSession) {
    commit(UPDATE_SESSIONLIST, {currentSession})
  }
}
